package net.crisps.cloud.log.config;

import org.apache.commons.lang3.StringUtils;
import org.springframework.boot.autoconfigure.condition.ConditionalOnBean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.annotation.Order;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import java.io.IOException;

/**
 * 增加过滤器，传递参数
 *
 * @author tanghm
 */
@Order(1)
@WebFilter(filterName = "httpServletRequestFilter", urlPatterns = "/*")
public class RequestFilter implements Filter {

    String contentType = "multipart/form-data";

    @Override
    public void init(FilterConfig filterConfig) throws ServletException {

    }

    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
        ServletRequest requestWrapper = null;
        if(StringUtils.isNotBlank(request.getContentType())&& !request.getContentType().contains(contentType) && request instanceof HttpServletRequest) {
            requestWrapper = new RequestWrapper((HttpServletRequest) request);

        }
        //获取request请求中的流，将取出来的字符串保存在缓存中，同时再将该字符串再次转换成流，然后把它放入到新request对象中。
        if (requestWrapper == null) {
            chain.doFilter(request, response);
        } else {
            chain.doFilter(requestWrapper, response);
        }
    }

    @Override
    public void destroy() {

    }

}
